/*
 * @Author: 徐凯 xukai@sinoroad.com
 * @Date: 2023-06-09 09:19:18
 * @Description: 屏幕适配
 */
import { onMounted, onBeforeUnmount, ref } from 'vue'

export default function useAutoFit() {
  // 定时器
  let drawTiming = ref(null)

  onMounted(() => {
    calcScaleRate()
    window.addEventListener('resize', resize)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resize)
  })

  // * 默认缩放值
  const scale = {
    width: '1',
    height: '1'
  }

  // * 设计稿尺寸（px）
  const baseWidth = 1920
  const baseHeight = 1080

  // * 需保持的比例（默认1.77778）
  const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))

  /**
   * 计算缩放比例
   * @returns
   */
  const calcScaleRate = () => {
    let appRef = document.getElementById('yuntu-container')
    if (!appRef) return
    // 当前宽高比
    const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
    if (appRef) {
      if (currentRate > baseProportion) {
        // 表示更宽
        scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
        scale.height = (window.innerHeight / baseHeight).toFixed(5)
        appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
      } else {
        // 表示更高
        scale.height = (window.innerWidth / baseProportion / baseHeight).toFixed(5)
        scale.width = (window.innerWidth / baseWidth).toFixed(5)
        appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
      }
    }
  }

  /**
   * 监听浏览器窗口大小变化
   */
  const resize = () => {
    clearTimeout(drawTiming.value)
    drawTiming.value = setTimeout(() => {
      calcScaleRate()
    }, 100)
  }
}
